package com.liuyongyi.livepush.Activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.liuyongyi.livepush.IScreenRecorderAidlInterface;
import com.liuyongyi.livepush.R;
import com.liuyongyi.livepush.base.BaseActivity;
import com.liuyongyi.livepush.bean.DanmakuBean;
import com.liuyongyi.livepush.core.RESAudioClient;
import com.liuyongyi.livepush.core.RESCoreParameters;
import com.liuyongyi.livepush.rtmp.RESFlvData;
import com.liuyongyi.livepush.rtmp.RESFlvDataCollecter;
import com.liuyongyi.livepush.service.ScreenRecordListenerService;
import com.liuyongyi.livepush.task.RtmpStreamingSender;
import com.liuyongyi.livepush.task.ScreenRecorder;
import com.liuyongyi.livepush.tool.LogTools;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//参考地址：https://github.com/eterrao/ScreenRecorder
public class ScreenPushActivity extends BaseActivity {
    private EditText pushurl;
    private MediaProjectionManager mMediaProjectionManager;
    private ScreenRecorder mVideoRecorder;
    private boolean isRecording;
    private static final int RESULTCODE = 10001;
    private String pushAddr;
    private RtmpStreamingSender streamingSender;
    private RESCoreParameters parameters;
    private RESAudioClient audioClient;
    private ExecutorService executorService;
    private Button start;
    private List<DanmakuBean> danmakuBeanList = new ArrayList<>();



    private IScreenRecorderAidlInterface recorderAidlInterface;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            recorderAidlInterface = IScreenRecorderAidlInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            recorderAidlInterface = null;
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_push);
        initView();

    }

    private void initView() {
        pushurl = findViewById(R.id.pushurl);
        mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        start = findViewById(R.id.start);
    }

    public void startPush(View view){
        if(mVideoRecorder != null){
            //结束
            stopScreenRecord();
        }else {
            //创建
            createScreenCapture();
        }
    }

    private void stopScreenRecord() {
        mVideoRecorder.quit();
        mVideoRecorder = null;
        if (streamingSender != null) {
            streamingSender.sendStop();
            streamingSender.quit();
            streamingSender = null;
        }
        if (executorService != null) {
            executorService.shutdown();
            executorService = null;
        }
        start.setText("重新录屏");
        audioClient.stop();
        audioClient.destroy();

    }

    private void createScreenCapture() {
        isRecording = true;
        Intent intent = mMediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(intent,RESULTCODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == RESULTCODE){
            MediaProjection mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode,data);
            if(mMediaProjection == null){
                LogTools.e("MediaProjection is null");
                return;
            }
            pushAddr = pushurl.getText().toString().trim();
            if(TextUtils.isEmpty(pushAddr)){
                LogTools.e("pushurl is null");
                return;
            }
            streamingSender = new RtmpStreamingSender();
            streamingSender.sendStart(pushAddr);

            RESFlvDataCollecter collecter = new RESFlvDataCollecter() {
                @Override
                public void collect(RESFlvData flvData, int type) {
                    if(streamingSender!= null){
                        streamingSender.sendFood(flvData,type);
                    }
                }
            };

            parameters = new RESCoreParameters();

            audioClient = new RESAudioClient(parameters);

            if(!audioClient.prepare()){
                LogTools.e("audioClient.prepare()failed");
                return;
            }

            mVideoRecorder = new ScreenRecorder(collecter,RESFlvData.VIDEO_WIDTH,RESFlvData.VIDEO_HEIGHT,RESFlvData.VIDEO_BITRATE,1,mMediaProjection);
            mVideoRecorder.start();
            audioClient.start(collecter);


            executorService = Executors.newCachedThreadPool();
            executorService.execute(streamingSender);

            start.setText("停止直播");
            Toast.makeText(this,"正在开始录屏",Toast.LENGTH_SHORT).show();
            moveTaskToBack(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mVideoRecorder != null) {
            stopScreenRecord();
            audioClient.destroy();
        }
        unbindService(connection);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isRecording) stopScreenRecordService();
    }

    private void stopScreenRecordService() {
        Intent runningServiceIT = new Intent(this, ScreenRecordListenerService.class);
        stopService(runningServiceIT);
        if (mVideoRecorder != null && mVideoRecorder.getStatus()) {
            Toast.makeText(this, "现在正在进行录屏直播哦", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isRecording) startScreenRecordService();
    }

    private void startScreenRecordService() {
        if (mVideoRecorder != null && mVideoRecorder.getStatus()) {
            Intent runningServiceIT = new Intent(this, ScreenRecordListenerService.class);
            bindService(runningServiceIT, connection, BIND_AUTO_CREATE);
            startService(runningServiceIT);
            startAutoSendDanmaku();
        }
    }

    private void startAutoSendDanmaku() {
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(new Runnable() {
            @Override
            public void run() {
                int index = 0;
                while (true) {
                    DanmakuBean danmakuBean = new DanmakuBean();
                    danmakuBean.setMessage(String.valueOf(index++));
                    danmakuBean.setName("little girl");
                    danmakuBeanList.add(danmakuBean);
                    try {
                        if (recorderAidlInterface != null) {
                            recorderAidlInterface.sendDanmaku(danmakuBeanList);
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
